// src/router/permission.js
import router from "./index";
import LayoutContainerThree from "@/views/LayoutContainerThree.vue";

/**
 * 初始化权限路由
 * @param {Array} backendRoutes 后端返回的路由信息
 */
// import { useUserStore } from "@/stores/user";
// const userStore = useUserStore();
function transformRoutes(backendRoutes) {
  console.log(backendRoutes, "backendRoutes111");

  const modules = import.meta.glob("../views/**/*.vue");
  return backendRoutes.map((route) => {
    console.log(route, "route.component");

    // 如果 component 为空或 null，设置为默认组件或重定向
    if (!route.component) {
      // route.component = () => import("@/views/EmptyComponent.vue"); // 默认组件
      // 或者重定向到子路由;
      // route.redirect = route.children[0].path;
    } else {
      // 使用 import.meta.glob 动态导入组件
      route.component = modules[`../views${route.component}.vue`];
    }

    const transformedRoute = {
      path: route.path,
      name: route.name,
      component: route.component,
      meta: {
        title: route.title,
        icon: route.icon,
      },
    };

    // 如果有子路由，递归处理
    if (route.children && route.children.length > 0) {
      transformedRoute.children = transformRoutes(route.children);
    }

    return transformedRoute;
  });
}

export function addDynamicRoutes(backendRoutes) {
  // 转换路由格式
  const transformedRoutes = transformRoutes(backendRoutes);
  console.log(transformedRoutes, "transformedRoutes");

  router.addRoute({
    path: "/",
    name: "LayoutContainer",
    component: LayoutContainerThree,
    // component: () => import("@/views/LayoutContainerThree.vue"),

    redirect: "/board",
    children: transformedRoutes,
  });
}

// export function initPermission(backendRoutes) {
//   // 动态添加路由
//   addDynamicRoutes(backendRoutes);
// }
